package com.punai.gk.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punai.common.bos.KVBO;
import com.punai.common.exception.ServiceException;
import com.punai.common.utils.DictUtils;
import com.punai.common.utils.SecurityUtils;
import com.punai.gk.domain.GkItem;
import com.punai.gk.domain.GkTemplate;
import com.punai.gk.domain.constants.GkConstants;
import com.punai.gk.mapper.GkItemMapper;
import com.punai.gk.mapper.GkTemplateMapper;
import com.punai.gk.service.IGkTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 归口模板Service业务层处理
 *
 * @author zxw_
 * @date 2023-01-06
 */
@Service
public class GkTemplateServiceImpl extends ServiceImpl<GkTemplateMapper,GkTemplate> implements IGkTemplateService
{
    @Autowired
    private GkTemplateMapper gkTemplateMapper;
    @Autowired
    private GkItemMapper gkItemMapper;

    /**
     * 查询归口模板
     *
     * @param id 归口模板主键
     * @return 归口模板
     */
    @Override
    public GkTemplate selectGkTemplateById(String id)
    {
        return gkTemplateMapper.selectGkTemplateById(id);
    }

    /**
     * 查询归口模板列表
     *
     * @param gkTemplate 归口模板
     * @return 归口模板
     */
    @Override
    public List<GkTemplate> selectGkTemplateList(GkTemplate gkTemplate)
    {
        return gkTemplateMapper.selectList(
                Wrappers.<GkTemplate>lambdaQuery()
                        .eq(GkTemplate::getCompanyId, SecurityUtils.getCompanyId())
                .orderBy(true,false,GkTemplate::getCreateTime)
        );
    }

    /**
     * 新增归口模板
     *
     * @param gkTemplate 归口模板
     * @return 结果
     */
    @Override
    @Transactional
    public int insertGkTemplate(GkTemplate gkTemplate)
    {
        Long companyId = SecurityUtils.getCompanyId();
        gkTemplate.setCompanyId(companyId);
        if (isExist(gkTemplate.getType(),gkTemplate.getName(),gkTemplate.getId())) {
            throw new ServiceException("存在相同的名称,类型模板!");
        }
        gkTemplateMapper.insert(gkTemplate);
        String templateId = gkTemplate.getId();
        int i = 1;
        // 默认参数
        for (GkConstants.GK_DEF_COLUMN value : GkConstants.GK_DEF_COLUMN.values()) {
            GkItem gkItem = new GkItem();
            gkItem.setCodeDesc(value.getCodeDesc());
            gkItem.setNameDesc(value.getNameDesc());
            gkItem.setTypeDesc(value.getTypeDesc());
            gkItem.setHide(value.getHide());
            gkItem.setCompanyId(companyId);
            gkItem.setTemplateId(templateId);
            gkItem.setOrderNum(i++);
            gkItemMapper.insert(gkItem);
        }
        return 1;
    }

    /**
     * 修改归口模板
     *
     * @param gkTemplate 归口模板
     * @return 结果
     */
    @Override
    public int updateGkTemplate(GkTemplate gkTemplate)
    {

        if (isExist(gkTemplate.getType(),gkTemplate.getName(),gkTemplate.getId())) {
            throw new ServiceException("存在相同的名称,类型模板!");
        }

        LambdaQueryWrapper<GkTemplate> eq = Wrappers.<GkTemplate>lambdaQuery()
                .eq(GkTemplate::getCompanyId, SecurityUtils.getCompanyId())
                .eq(GkTemplate::getId, gkTemplate.getId());
        return gkTemplateMapper.update(gkTemplate,eq);
    }

    private boolean isExist(String type,String name,String id) {

        List<GkTemplate> gkTemplates = gkTemplateMapper.selectList(
                Wrappers.<GkTemplate>lambdaQuery()
                        .eq(GkTemplate::getCompanyId, SecurityUtils.getCompanyId())
                        .eq(GkTemplate::getType, type)
                        .eq(GkTemplate::getName, name)
        );
        if (gkTemplates.size() == 1) {
            GkTemplate gkTemplate = gkTemplates.get(0);
            String id1 = gkTemplate.getId();
            return !StrUtil.equals(id1, id);
        }
        return gkTemplates.size() > 1;
    }


    /**
     * 批量删除归口模板
     *
     * @param ids 需要删除的归口模板主键
     * @return 结果
     */
    @Override
    public int deleteGkTemplateByIds(String[] ids)
    {
        return gkTemplateMapper.deleteGkTemplateByIds(ids);
    }

    /**
     * 删除归口模板信息
     *
     * @param id 归口模板主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteGkTemplateById(String id)
    {
        gkTemplateMapper.delete(
                Wrappers.<GkTemplate>lambdaQuery()
                        .eq(GkTemplate::getId, id)
                        .eq(GkTemplate::getCompanyId, SecurityUtils.getCompanyId())
        );

        gkItemMapper.delete(
                Wrappers.<GkItem>lambdaQuery()
                        .eq(GkItem::getCompanyId, SecurityUtils.getCompanyId())
                        .eq(GkItem::getTemplateId, id)
        );
        return 1;
    }

    @Override
    public String getTemplateId(String gkName, String gkType) {

        GkTemplate gkTemplate = gkTemplateMapper.selectOne(
                Wrappers.<GkTemplate>lambdaQuery()
                        .eq(GkTemplate::getName, gkName)
                        .eq(GkTemplate::getType, gkType)
        );
        if (gkTemplate == null) {
            return "";
        }
        return gkTemplate.getId();
    }

    @Override
    public List<GkItem> getTemplateColumn(String templateId) {
        List<GkItem> gkItems = gkItemMapper.selectList(
                Wrappers.<GkItem>lambdaQuery()
                        .eq(GkItem::getTemplateId, templateId)
                        .orderByAsc(GkItem::getCodeDesc)
        );
        String codeDescId = GkConstants.GK_DEF_COLUMN.ID.getCodeDesc();
        String codeDescPid = GkConstants.GK_DEF_COLUMN.PID.getCodeDesc();
        List<String> excludeCodes = new ArrayList<>();
        excludeCodes.add(codeDescId);
        excludeCodes.add(codeDescPid);
        List<GkItem> collect = gkItems.stream().filter(e -> !excludeCodes.contains(e.getCodeDesc())).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<KVBO> getTemplateLinkFeeType(String templateId) {

        GkTemplate gkTemplate = gkTemplateMapper.selectOne(
                Wrappers.<GkTemplate>lambdaQuery()
                        .eq(GkTemplate::getCompanyId, SecurityUtils.getCompanyId())
                        .eq(GkTemplate::getId, templateId)
        );
        String useFeetype = gkTemplate.getUseFeetype();
        List<KVBO> bos = new ArrayList<>();
        if (StrUtil.isNotEmpty(useFeetype)) {
            List<String> split = StrUtil.split(useFeetype, ",");
            for (String feeType : split) {
                KVBO kv2bo = new KVBO();
                String dictLabel = DictUtils.getDictLabel("fee_categorys", feeType);
                kv2bo.setKey(dictLabel);
                kv2bo.setValue(feeType);
                bos.add(kv2bo);
            }
        }
        return bos;
    }
}
